#!/bin/bash
clear
if [[ "$EUID" -ne 0 ]]; then
    echo -e "\033[1;31mScript need to be run as root!\033[0m"; exit 1
fi

echo "deb http://deb.debian.org/debian buster-backports main" | tee /etc/apt/sources.list.d/buster-backports.list

apt-get -qq update
apt-get -y -qq install wireguard
apt-get -y -qq install wireguard-tools
apt-get -y -qq install wireguard-dkms
apt-get -y -qq install linux-headers-$(uname -r)
apt-get -y -qq install qrencode

if [[ ! -d /etc/wireguard/clients ]]; then
    mkdir -p /etc/wireguard/clients
    mkdir -p /etc/wireguard/clients/cybertize
    touch /etc/wireguard/clients/.accounts
fi

alamat_ip=$(wget -qO- ipv4.icanhazip.com)
alamat_hos=$(cat /etc/environment | grep -w 'DOMAIN' | cut -d '=' -f 2)
server_private_key=$(wg genkey)
server_public_key=$(echo "$server_private_key" | wg pubkey)
client_private_key=$(wg genkey)
client_public_key=$(echo "$client_private_key" | wg pubkey)
preshared_key=$(wg genpsk)
peer_port=$(shuf -i1024-65535 -n1)
nama_pengguna=$(cat /etc/environment | grep -w 'USERNAME' | cut -d '=' -f 2)

cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.80.0.0/24
ListenPort = 51820
PrivateKey = $server_private_key
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE;
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE;
SaveConfig = false

# $nama_pengguna start
[Peer]
PublicKey = $client_public_key
PresharedKey = $preshared_key
AllowedIPs = 10.80.0.1/32
# $nama_pengguna end
EOF

cat >> /etc/wireguard/clients/$nama_pengguna/$nama_pengguna.conf <<EOF
# $nama_pengguna
[Interface]
Address = 10.80.0.1/32
DNS = 8.8.8.8,8.8.4.4
ListenPort = $peer_port
MTU = 1280
PrivateKey = $client_private_key

[Peer]
AllowedIPs = 0.0.0.0/0
Endpoint = $cybertize.ml:51820
PersistentKeepalive = 300
PresharedKey = $preshared_key
PublicKey = $server_public_key
EOF

# Generate QR Code
qrencode -m 2 -t ansiutf8 \
-o "/etc/wireguard/clients/$nama_pengguna/$nama_pengguna.png" \
-r "/etc/wireguard/clients/$nama_pengguna/$nama_pengguna.conf"

systemctl enable wg-quick@wg0
systemctl restart wg-quick@wg0

echo
echo -e "\033[1;32mCongratulation, We are done with the wireguard installation.\033[0m"
echo
echo 'Use my referral link https://m.do.co/c/a28a40414d6a'
echo 'to gets $100 credit into your DigitalOcean account.'
echo 'Created by Doctype, Powered by Cybertize'
echo 'Copyright 2021, Allright reserved.'
echo; sleep 5
